/**
 * AI收藏图片网格组件
 */
import React, { useState, useEffect, useRef, useCallback } from 'react';
import { request } from '@/api/request';
import { useTranslation } from 'react-i18next';
import ImageViewer from '@/components/ImageViewer';
import { useMessage } from '@/components/messageApi';
import { SortOption } from './Collection_CollectionHeader';

// 新的图片项类型定义
interface ImageItem {
  task_id: string;
  image_url: string;
  completed_at: string;
}

interface AICollectionGridProps {
  ai_person_id: any;
  sortBy?: SortOption; // 排序方式
  // 添加管理模式相关属性
  isManageMode?: boolean;
  selectedImages?: string[];
  onSelectedImagesChange?: (selectedImages: string[]) => void;

}

const AICollectionGrid: React.FC<AICollectionGridProps> = ({ 
  ai_person_id, 
  sortBy = 'newest',
  isManageMode = false,
  selectedImages = [],
  onSelectedImagesChange
}) => {
  const { t } = useTranslation();
  const message = useMessage();
  const [images, setImages] = useState<ImageItem[]>([]);
  const [loading, setLoading] = useState(false);
  const [loadingMore, setLoadingMore] = useState(false);
  const [error, setError] = useState<string>('');
  const [currentPage, setCurrentPage] = useState(1);
  const [hasMore, setHasMore] = useState(true);
  const [isInitialLoad, setIsInitialLoad] = useState(true);
  const [totalCount, setTotalCount] = useState(0);

  // 防止重复请求的ref
  const isRequestingRef = useRef(false);

  // 图片预览相关状态
  const [showImageViewer, setShowImageViewer] = useState(false);
  const [currentViewerImage, setCurrentViewerImage] = useState('');

  // 用于引用最后一个图片元素的ref
  const lastImageRef = useRef<HTMLDivElement>(null);

  // 调试标志，记录Observer是否已设置
  const observerSetupRef = useRef<boolean>(false);

  // 存储原始未排序的数据
  const [originalImages, setOriginalImages] = useState<ImageItem[]>([]);

  // 排序图片函数
  const sortImages = useCallback((imagesToSort: ImageItem[], sort: SortOption): ImageItem[] => {
    if (!imagesToSort || imagesToSort.length === 0) return [];

    // 创建副本以避免直接修改原数组
    const sortedImages = [...imagesToSort];

    switch (sort) {
      case 'newest':
        // 按完成时间降序排列（最新的在前面）
        return sortedImages.sort((a, b) =>
          new Date(b.completed_at).getTime() - new Date(a.completed_at).getTime()
        );
      case 'oldest':
        // 按完成时间升序排列（最早的在前面）
        return sortedImages.sort((a, b) =>
          new Date(a.completed_at).getTime() - new Date(b.completed_at).getTime()
        );
      default:
        return sortedImages;
    }
  }, []);

  // 处理图片URL，添加OSS处理参数
  const processImageUrl = (url: string): string => {
    if (!url) return url;
    const separator = url.includes('?') ? '&' : '?';
    return `${url}${separator}`;
  };

  // 处理图片点击
  const handleImageClick = (imageItem: ImageItem, index: number) => {
    if (isManageMode) {
      // 管理模式下，点击图片进行选择/取消选择
      handleImageSelect(imageItem.task_id);
    } else {
      // 正常模式下，点击图片预览
      // console.log('点击图片:', { imageItem, index });
      const processedUrl = processImageUrl(imageItem.image_url);
      // console.log('处理后的图片URL:', processedUrl);
      setCurrentViewerImage(processedUrl);
      setShowImageViewer(true);
    }
  };

  // 处理图片选择
  const handleImageSelect = (taskId: string) => {
    if (!onSelectedImagesChange) return;
    
    const isSelected = selectedImages.includes(taskId);
    let newSelection: string[];
    
    if (isSelected) {
      // 取消选择
      newSelection = selectedImages.filter(id => id !== taskId);
    } else {
      // 添加选择
      newSelection = [...selectedImages, taskId];
    }
    
    onSelectedImagesChange(newSelection);
  };



  // 关闭图片预览
  const handleCloseImageViewer = () => {
    // console.log('Collection: 关闭图片预览');
    setShowImageViewer(false);
    setCurrentViewerImage('');
    // console.log('Collection: showImageViewer设置为false');
  };

  // 统一的数据加载函数
  const fetchData = useCallback(async (page: number, isInitial = false) => {
    // 如果没有ai_person_id，则不进行加载
    if (!ai_person_id) {
      // console.warn('ai_person_id 为空，无法获取图片数据');
      console.error('ai_person_id is empty, cannot get image data');
      return;
    }

    // 如果已经有请求在进行中，则不再发起新请求
    if (isRequestingRef.current) {
      // console.log('已有请求进行中，跳过此次请求');
      return;
    }

    // 如果正在加载更多且不是初始加载，或者没有更多数据了且不是初始加载，则不进行加载
    if ((loadingMore && !isInitial) || (!hasMore && !isInitial && page > 1)) {
      // console.log('跳过请求: loadingMore=', loadingMore, 'hasMore=', hasMore, 'isInitial=', isInitial, 'page=', page);
      return;
    }

    try {
      // 标记请求开始
      isRequestingRef.current = true;

      // 根据是否为初始加载设置不同的loading状态
      if (isInitial) {
        setLoading(true);
        setError('');
      } else {
        setLoadingMore(true);
      }

      // 正确获取用户数据
      const userDataStr = localStorage.getItem('userData');
      const userData = userDataStr ? JSON.parse(userDataStr) : null;
      const uuid = userData?.visitor_uuid;

      if (!uuid) {
        setError(t('collection.errors.userDataIncomplete'));
        isRequestingRef.current = false;
        return;
      }

      // console.log(`正在加载第 ${page} 页数据...`);

      const res = await request.post('/api/ai-person-image/getAicollection', {
        uuid: uuid,
        ai_person_id: ai_person_id,
        page: page,
        limit: 10
      });

      // console.log(`第 ${page} 页 API响应:`, res.data);

      if (res.data.success === true) {
        // 新的数据格式处理
        const newImages = res.data.data?.Images || [];
        const total = res.data.data?.total_count || 0;

        // 更新总数
        setTotalCount(total);

        if (newImages.length > 0) {
          // 保存原始未排序的数据
          if (isInitial) {
            setOriginalImages(newImages);
          } else {
            setOriginalImages(prev => [...prev, ...newImages]);
          }

          // 根据排序选项对新数据进行排序
          const sortedNewImages = sortImages(newImages, sortBy);

          // 根据是否为初始加载，设置或追加图片
          if (isInitial) {
            setImages(sortedNewImages);
          } else {
            // 合并并重新排序所有图片
            setImages(prevImages => {
              const combinedImages = [...prevImages, ...sortedNewImages];
              return sortImages(combinedImages, sortBy);
            });
          }

          setCurrentPage(page);
          // console.log(`成功加载第 ${page} 页，${isInitial ? '加载' : '新增'} ${newImages.length} 张图片`);

          // 计算当前已加载的图片总数（使用闭包捕获当前值以避免依赖项问题）
          setHasMore(prev => {
            // 获取当前加载的图片总数
            const currentTotal = isInitial
              ? newImages.length
              : (images.length + newImages.length);

            // 判断是否还有更多图片
            const hasMoreImages = currentTotal < total;

            // console.log(`已加载 ${currentTotal} 张图片，总数 ${total}，是否还有更多: ${hasMoreImages}`);
            return hasMoreImages;
          });
        } else {
          // 没有更多数据了
          setHasMore(false);
          // console.log('没有更多图片数据了');
        }
      } else {
        setError(res.data.message || (isInitial ? t('collection.errors.loadFailed') : t('collection.errors.loadMoreFailed')));
      }
    } catch (error) {
      // console.error(`${isInitial ? '获取' : '加载更多'}AI收藏图片失败:`, error);
      console.error(`${isInitial ? 'get' : 'load more'}AI collection image failed`,error);
      setError(t('collection.errors.networkError'));
    } finally {
      if (isInitial) {
        setLoading(false);
        setIsInitialLoad(false);
      } else {
        setLoadingMore(false);
      }
      // 请求结束后重置请求标志
      isRequestingRef.current = false;
    }
  }, [ai_person_id, hasMore, loadingMore, t, images.length, sortBy, sortImages]);

  // 加载更多数据
  const loadMoreData = useCallback(() => {
    // 避免初次加载后立即触发加载更多
    if (isInitialLoad || isRequestingRef.current) {
      // console.log('loadMoreData: 跳过请求 - 初始加载中或已有请求', { isInitialLoad, isRequesting: isRequestingRef.current });
      return;
    }

    // 检查是否还有更多数据
    if (!hasMore) {
      // console.log('loadMoreData: 没有更多数据了，跳过请求');
      return;
    }

    // console.log('loadMoreData: 开始加载下一页', currentPage + 1);
    fetchData(currentPage + 1, false);
  }, [fetchData, currentPage, isInitialLoad, hasMore]);

  // 当最后一个元素进入视口时的回调函数
  const handleLastImageIntersection = useCallback((entries: IntersectionObserverEntry[]) => {
    const [entry] = entries;
    if (entry && entry.isIntersecting) {
      // console.log('最后一张图片进入视口!', {
      //   isRequesting: isRequestingRef.current,
      //   hasMore,
      //   isInitialLoad
      // });

      // 即使当前有请求，也记录这次观察到了，便于调试
      if (!isRequestingRef.current && hasMore && !isInitialLoad) {
        // console.log('该加载数据啦！触发loadMoreData()');
        loadMoreData();
      } else {
        // console.log('不满足加载条件:', {
        //   isRequesting: isRequestingRef.current,
        //   hasMore,
        //   isInitialLoad
        // });
      }
    }
  }, [loadMoreData, hasMore, isInitialLoad]);

  // 设置Intersection Observer来监听最后一个图片元素
  useEffect(() => {
    const currentLastImageRef = lastImageRef.current;

    if (!currentLastImageRef || images.length === 0) {
      // console.log('没有找到最后一张图片元素，或图片列表为空，不设置Observer');
      return;
    }

    // console.log('设置Observer监听最后一张图片元素', images.length);
    observerSetupRef.current = true;

    const observer = new IntersectionObserver(handleLastImageIntersection, {
      root: null, // 使用视口作为根
      rootMargin: '100px', // 提前100px触发加载，增大触发区域
      threshold: 0.3 // 当30%的元素可见时就触发，降低触发门槛
    });

    observer.observe(currentLastImageRef);
    // console.log('Observer已设置，监听元素:', currentLastImageRef);

    // 清理函数
    return () => {
      if (currentLastImageRef) {
        observer.unobserve(currentLastImageRef);
        // console.log('Observer已清理');
      }
    };
  }, [images, handleLastImageIntersection]);

  // 组件挂载时获取初始数据，仅在ai_person_id变化时重新获取
  useEffect(() => {
    // 重置状态
    setCurrentPage(1);
    setHasMore(true);
    setIsInitialLoad(true);
    setTotalCount(0);
    setImages([]);
    setOriginalImages([]);
    // 重置Observer设置状态
    observerSetupRef.current = false;
    // 获取初始数据
    fetchData(1, true);

    // 清理函数，组件卸载或ai_person_id变化时执行
    return () => {
      // 确保所有进行中的请求被标记为取消
      isRequestingRef.current = false;
    };
  }, [ai_person_id]); // 只有当ai_person_id变化时才重新获取数据

  // 当排序方式变化时，重新对已加载的图片进行排序
  useEffect(() => {
    if (originalImages.length > 0) {
      // console.log('排序方式变更为:', sortBy);
      const newSortedImages = sortImages(originalImages, sortBy);
      setImages(newSortedImages);
    }
  }, [sortBy, originalImages, sortImages]);

  // 检查是否所有图片都已加载但没有触发懒加载（比如图片太少，最后一张没有进入Observer视野）
  useEffect(() => {
    // 如果已完成初始加载，有图片但数量少且还有更多可加载的，自动触发加载更多
    if (!isInitialLoad && !loadingMore && !isRequestingRef.current &&
      images.length > 0 && images.length < totalCount && hasMore &&
      images.length < 5) { // 图片数量少于5张时主动加载下一页
      // console.log('图片数量少，自动加载下一页', {
      //   imagesCount: images.length,
      //   totalCount,
      //   hasMore
      // });
      setTimeout(() => {
        loadMoreData();
      }, 500); // 短暂延迟以避免潜在的竞态条件
    }
  }, [images.length, isInitialLoad, loadingMore, totalCount, hasMore, loadMoreData]);



  return (
    <div className="w-full">
      {/* 图片网格内容区域 */}
      <div className="sm:p-4 md:p-6">

        {/* 响应式图片网格 */}
        {!loading && !error && (
          <div className="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5 xl:grid-cols-5 gap-4 sm:gap-5 md:gap-6">
            {images.map((imageItem, index) => {
              const isSelected = selectedImages.includes(imageItem.task_id);
              return (
                <div
                  key={imageItem.task_id}
                  ref={index === images.length - 1 ? lastImageRef : null}
                  className={`relative group cursor-pointer overflow-hidden rounded-lg bg-gray-800 transition-all duration-200 ${
                    isManageMode 
                      ? (isSelected ? 'ring-2 ring-pink-500 scale-95' : 'hover:scale-105') 
                      : 'hover:scale-105'
                  } ${index === images.length - 1 ? 'last-image' : ''}`}
                  style={{ aspectRatio: '9/16' }}
                  onClick={() => handleImageClick(imageItem, index)}
                >
                  {/* 管理模式下的选择框 */}
                  {isManageMode && (
                    <div className="absolute top-2 left-2 z-10">
                      <div className={`w-5 h-5 sm:w-6 sm:h-6 rounded-full border-2 flex items-center justify-center transition-all duration-200 ${
                        isSelected 
                          ? 'bg-pink-500 border-pink-500' 
                          : 'bg-black bg-opacity-50 border-white border-opacity-70 hover:border-pink-500'
                      }`}>
                        {isSelected && (
                          <i className="fas fa-check text-white text-xs sm:text-sm" />
                        )}
                      </div>
                    </div>
                  )}

                  <img
                  src={processImageUrl(imageItem.image_url)}
                  alt={t('collection.imageAlt', { index: index + 1 })}
                  className="w-full h-full object-cover transition-opacity duration-300"
                  loading="lazy"
                  onError={(e) => {
                    const target = e.target as HTMLImageElement;
                    target.style.display = 'none';
                    // console.error('图片加载失败:', imageItem.image_url);
                    console.error('image loading failed', imageItem.image_url);
                  }}
                />

                                  {/* 悬停遮罩 - 仅在非管理模式下显示 */}
                  {!isManageMode && (
                    <div className="absolute inset-0 bg-black bg-opacity-0 group-hover:bg-opacity-30 transition-all duration-200 flex items-center justify-center">
                      <i className="fas fa-search-plus text-white opacity-0 group-hover:opacity-100 transition-opacity duration-200 text-xl" />
                    </div>
                  )}

                {/* 最后一张图片的标记，便于调试 */}
                {index === images.length - 1 && images.length < totalCount && (
                  <div className="absolute top-0 right-0 bg-pink-500 text-white text-xs px-1 rounded-bl">
                    {images.length}/{totalCount}
                  </div>
                )}
                </div>
              );
            })}
          </div>
        )}

        {/* 加载更多状态 */}
        {loadingMore && (
          <div className="flex items-center justify-center py-8">
            <div className="text-center text-gray-400">
              <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-pink-500 mx-auto mb-2"></div>
              <div className="text-sm">{t('collection.loadingMore')}</div>
            </div>
          </div>
        )}

        {/* 没有更多数据提示 */}
        {!loading && !error && images.length > 0 && !hasMore && !loadingMore && (
          <div className="flex items-center justify-center py-8 text-gray-500">
            <div className="text-center">
              <i className="fas fa-check-circle text-2xl mb-2" />
              <div className="text-sm">{t('collection.allImagesLoaded')}</div>
              <div className="text-xs text-gray-400">{t('collection.totalImages', { count: totalCount })}</div>
            </div>
          </div>
        )}

        {/* 无数据状态 */}
        {!loading && !error && images.length === 0 && (
          <div className="flex items-center justify-center py-8 text-gray-500">
            <div className="text-center">
              <i className="fas fa-image text-3xl mb-4" />
              <div className="text-lg mb-2">{t('collection.noImages')}</div>
              <div className="text-sm">{t('collection.noImagesDesc')}</div>
            </div>
          </div>
        )}

        {/* 手动加载更多按钮，在有更多数据但懒加载失效时显示 */}
        {!loading && !loadingMore && !error && images.length > 0 && hasMore && (
          <div className="flex justify-center mt-6 mb-4">
            <button
              className="px-4 py-2 bg-pink-600 hover:bg-pink-700 text-white rounded-lg transition-colors"
              onClick={() => loadMoreData()}
            >
              {t('collection.loadMore')}
            </button>
          </div>
        )}
      </div>

      {/* 图片预览组件 */}
      <ImageViewer
        show={showImageViewer}
        imageUrl={currentViewerImage}
        imageAlt={t('collection.imagePreviewAlt')}
        onClose={handleCloseImageViewer}
      />
    </div>
  );
};

export default AICollectionGrid; 